<?php
/**
 * Created by PhpStorm.
 * User: saeb
 * Date: 12/10/18
 * Time: 1:12 AM
 */
require(tiremanager_plugin_dir_path . 'formsconfig.php');
if ($tire_ware_house_limit) {

    foreach ($tire_gf_fields_id_quantity_asked as $tire_quantity_gf_field_id => $value) {
        add_filter("gform_field_validation_" . $tire_gravity_form_id . "_" . "$tire_quantity_gf_field_id",
            'tire_quantity_check', 10, 4); //add gform tire quantity validator
    }
}

if ($tire_seller_days_limit) {
    foreach ($tire_delivery_date_field_id as $delivery_day => $value) {
        add_filter("gform_field_validation_" . $tire_gravity_form_id . "_" . "$delivery_day",
            'tire_signup_per_day_limit', 10, 4); //mahdoodiat roozane sabte nam be har aamel
    }
}
if ($today_seller_signup_limit) {
    foreach ($tire_gf_fields_id_sellers_array as $seller => $value) {
        add_filter("gform_field_validation_" . $tire_gravity_form_id . "_" . "$seller",
            'seller_today_signup_limit', 10, 4); //mahdoodiat roozane sabte nam be har aamel
    }
}
function tire_quantity_check($result, $value, $form, $field)
{
//	if(WP_DEBUG) return $result;
	error_log('we are in validator');
    //https://docs.gravityforms.com/gform_field_validation/
    require(tiremanager_plugin_dir_path . 'formsconfig.php');
    require(tiremanager_plugin_dir_path . 'sellers_brands.php');
    global $wpdb;
    $tire_quantity = intval($value);
    $tire_size = "";
    $tire_brand = "";
    $tire_seller = "";
    $tire_delivery_day = "";

    foreach ($tire_gf_fields_id_sellers_array as $tire_sabok_seller_gf_field_id => $value) {
        $tire_seller = $tire_seller . rgpost("input_$tire_sabok_seller_gf_field_id");
      //   error_log("tire_seller");
    //    error_log($tire_seller);
               


    }
    $seller_fa = $sellers_array[$tire_seller]['farsi_name'];


    foreach ($sellers_array[$tire_seller]['tire_type'] as $type) {

        foreach ($tire_gf_fields_id_tire_sizes[$type] as $tire_sabok_size_gf_field_id => $value) {
            $tire_size = $tire_size . rgpost("input_$tire_sabok_size_gf_field_id");
        }
    }
    foreach ($tire_gf_fields_id_brands_array as $tire_sabok_brand_gf_field_id => $value) {
        $tire_brand = $tire_brand . rgpost("input_$tire_sabok_brand_gf_field_id");

    }
    $brand_fa = $brands_array[$tire_brand]['farsi_name'];


    $available_tires = $wpdb->get_var("
    select `tire_quantity` from $wpdb->prefix$tire_table_quantities_without_prefix_name
    where id = (
SELECT max(id) from $wpdb->prefix$tire_table_quantities_without_prefix_name where 
    `tire_seller` = '$tire_seller'
    and `tire_size`= '$tire_size' 
    and `tire_brand`= '$tire_brand'
)
    ");

    if ($tire_quantity > ($available_tires) && $result['is_valid']) {
        $result['is_valid'] = false;
        $result['message'] = "
            لاستیک 
            $brand_fa
             سایز
            $tire_size
            موجود نمی باشد.
            ";
    }

    return $result;


}
function jalaliepoch($jalali_date,$sep='-'){//YYYY-mm-dd
    require_once(tiremanager_plugin_dir_path . 'lib/G2Hijri.php');
    require(tiremanager_plugin_dir_path . 'formsconfig.php');

    $jdate_array = explode($sep,$jalali_date);
    list ($year,$month,$day) = jalali_to_gregorian($jdate_array[0],
        $jdate_array[1],
        $jdate_array[2]);
    $date=$year."-".$month."-".$day;
    $hijri_array = Greg2Hijri($day,$month,$year);
    $hijri_array['day']+=$hijri_diffrence;
    return array(
        'jalali' => array('year'=>$jdate_array[0],
                            'month'=>$jdate_array[1],
            'day'=>$jdate_array[2]
    ),
        'miladi'=>array(
            'year'=>$year,
            'month'=>$month,
            'day'=>$day,
        ),
        'day_epoch'=>mktime(0,0,0,$day,$month,$year),
        'date'=>date_create($date),
        'hijri'=>$hijri_array,

        );

}


function tire_signup_per_day_limit($result, $value, $form, $field)
{
    require(tiremanager_plugin_dir_path . 'formsconfig.php');
    require(tiremanager_plugin_dir_path . 'sellers_brands.php');
	if(!function_exists("is_tatil")) {
		require( tiremanager_plugin_dir_path . 'index.php' );
	}    date_default_timezone_set('Asia/Tehran');
    $tire_seller = "";
    $tire_delivery_day1 =explode("-",$value);
    $jyear=$tire_delivery_day1[0];
    $jmonth=$tire_delivery_day1[1];
    $jday=$tire_delivery_day1[2];
    $jselected_day=$jyear."-".$jmonth."-".$jday;
    $today_jalali=jdate('Y-m-d',time(),false,false);
    $hour_now = intval(date('G'));
    $selected_day_epoch = jalaliepoch($jselected_day);
    $today_epoch = jalaliepoch($today_jalali);
    $days_diff =date_diff($today_epoch[ 'date'],$selected_day_epoch['date']);
    $is_passed=$days_diff->invert; // mishe 1 age rooz entekhabi ghadimitar az emrooz bashe

    if (is_tatil($jselected_day) > 5){
        $result['is_valid']=false;
        $result['message']="روز تعطیل قابل انتخاب نمی‌باشد";
    };


    if (WP_DEBUG){
        error_log(print_r($days_diff,true));
//    error_log("today:");
//    error_log(print_r($selected_day_epoch,true));
//    error_log(print_r(is_tatil($jselected_day),true));
//    error_log("date of form: ");
//    error_log(print_r(jalaliepoch("$jyear"."-"."$jmonth"."-".$jday),true));
//    error_log("diff= ".$days_diff);

    }
    $tire_delivery_day=$jyear."-".$jmonth."-".$jday;
//    error_log(print_r($tire_delivery_day,true));
    foreach ($tire_gf_fields_id_sellers_array as $tire_sabok_seller_gf_field_id => $value) {
        $tire_seller = $tire_seller . rgpost("input_$tire_sabok_seller_gf_field_id");

    }
    $seller_fa = $sellers_array[$tire_seller]['farsi_name'];
    $entry_count = 0;
    foreach ($tire_delivery_date_field_id as $day=>$value){
    foreach ($tire_gf_fields_id_sellers_array as $sf => $value) {
        $search_criteria = array();
        $search_criteria['field_filters'][] = array('key' => "$day", 'value' => "$tire_delivery_day");
        $search_criteria['field_filters'][] = array('key' => "$sf", 'value' => "$tire_seller");
        $entry = GFAPI::count_entries($tire_gravity_form_id, $search_criteria);
        $entry_count = $entry_count + $entry;
//        error_log("==========\n".print_r($search_criteria,true).$entry_count);
    }}
//    error_log("entry code $entry_count  limit $tire_seller_days_limitation");
    if (intval($entry_count) >= $tire_seller_days_limitation) {
//        error_log("we are in");
        $result['is_valid'] = false;
        $result['message'] = "
                ظرفیت ثبت نامی 
                 عامل
                $seller_fa 
                در روز 
                $tire_delivery_day
                پر شده است. لطفا تاریخ تحویل یا عامل فروش را تغییر دهید.
                ";
    }
    error_log("passed".$is_passed);
    if ($is_passed == 1 or $days_diff->days == 0) {
        $result['is_valid']=false;
        $result['message']="
       تاریخ مورد نظر باید از روزهای آتی باشد
        ";
    }
    return $result;

}
function seller_today_signup_limit($result, $value, $form, $field){
    //err_log("we are in seller_today_signup_limit");
	require(tiremanager_plugin_dir_path . 'formsconfig.php');
	$start_date = date( 'Y-m-d', time() );
	$entries=[];
	$count =0 ;
	/** @var array $tire_gf_fields_id_sellers_array */
	foreach ($tire_gf_fields_id_sellers_array as $seller=>$v){
		$search_criteria=[];
		$search_criteria['start_date'] = $start_date;
		$search_criteria['field_filters'][] = array( 'key' => "$seller", 'value' => "$value" );
		$count = $count + GFAPI::count_entries($tire_gravity_form_id,$search_criteria);
		$entries = array_merge($entries,GFAPI::get_entries($tire_gravity_form_id,$search_criteria));


	}
if($count >= $tire_seller_days_limitation) {
	$result['is_valid'] = false;
	$result['message']  = "ظرفیت این عامل تکمیل شده است ! عامل دیگری را انتخاب نمایید.";
};
	return $result;
}
